const CryptoJS = require("crypto-js");

const axios = require('axios');  
  



// const adc = 'ee6c0bfc79e0d22d88e08fdbbd0fcafa';
async function fetchPowerData(accessToken1){
    

    // 加载.env文件  
      

    // 现在你可以通过process.env来访问环境变量  
    var timestamp = getTime();
   

    const clientId = 'rap5yyd478qnpywrd8df';
    const secret = 'f370771495cc4c66951b818c328cf19b';
    const accessToken = accessToken1;
    // var accessToken = "";  
    // if (process.env.hasOwnProperty("EASY_ACCESS_TOKEN") && process.env.EASY_ACCESS_TOKEN) {  
    //     accessToken = process.env.EASY_ACCESS_TOKEN;  
    // }

    const httpMethod = 'GET';
    const query = [  
        
      ];  

    
    
    // sha256
    var signMap = stringToSign(query, httpMethod)

    var signStr = signMap["signUrl"]
    var nonce = ""
    var sign = calcSign(clientId,accessToken, timestamp, nonce, signStr, secret);
    process.env.TOKEN_SIGN = sign;  
 
const tokenheaders = {  
    'sign_method': 'HMAC-SHA256',  
    'client_id': 'rap5yyd478qnpywrd8df',  
    't': timestamp,  
    'mode': 'cors',  
    'Content-Type': 'application/json',  
    'sign': sign,  
    'access_token':accessToken1,
  };  

  try {
    // 使用 await 等待 Promise 解决
    const response = await axios.get('https://openapi.tuyacn.com/v1.0/devices/6cd2bd75ba8a2e86f98jrt/status', {
      headers: tokenheaders,
      params: {
        // 如果需要传递额外的GET参数，可以在这里添加
      }
    })

    // 请求成功，处理响应数据
    const phaseAObject = response.data.result.find(item => item.code === 'phase_a');

    if (phaseAObject) {
      // 假设 phaseAValue 是 base64 编码的字符串
      const phaseAValueBase64 = phaseAObject.value;

      // 使用 atob() 函数解码 base64 字符串
      const phaseAValueBinaryString = atob(phaseAValueBase64);

      // 创建一个长度与解码字符串相同的 Uint8Array
      const buffer = new Uint8Array(phaseAValueBinaryString.length);

      // 将解码的字符串中的每个字符转换为 Uint8Array 中的一个字节
      for (let i = 0; i < phaseAValueBinaryString.length; i++) {
        buffer[i] = phaseAValueBinaryString.charCodeAt(i);
      }

      // 现在您可以使用 buffer 来获取电压、电流和功率的值
      // 注意：这里的索引和计算可能需要根据实际情况调整
      const voltageHex = buffer.slice(0, 2); // 前两个字节
      const currentHex = buffer.slice(2, 5); // 接下来的三个字节
      const powerHex = buffer.slice(5, 8); // 最后的三个字节

      // 将字节转换为十进制数值
      const voltageDec =( (voltageHex[0] << 8) | voltageHex[1])*0.1;
      const currentDec = ((currentHex[0] << 16) | (currentHex[1] << 8) | currentHex[2])*0.01;
      const powerDec =((powerHex[0] << 16) | (powerHex[1] << 8) | powerHex[2])*0.001;

      // 返回格式化后的电压、电流和功率值
      return {
        voltage: voltageDec.toFixed(1),
        current: currentDec.toFixed(2),
        power: powerDec.toFixed(3)
      };
     
    } else {
      console.log('未找到code为phase_a的字段');
    }
  } catch (error) {
    // 请求失败，输出错误信息
    console.error("发生错误:", error);
    // 这里可以选择抛出错误，或者返回一个特定的值表示失败
    throw error; // 抛出错误，让调用者处理
  }
}

module.exports = { fetchPowerData };
function getTime(){
    var timestamp = new Date().getTime();
    return timestamp;
}

// 令牌验签计算
// function calcSign(clientId,timestamp,nonce,signStr,secret){
//     var str = clientId +timestamp + nonce + signStr;
//     console.log("str:",str);
//     var hash = CryptoJS.HmacSHA256(str, secret);
//     var hashInBase64 = hash.toString();
//     var signUp = hashInBase64.toUpperCase();
//     console.log("sign:",signUp)
//     console.log("t:",timestamp)
//     return signUp;
// }

// 业务验签计算
function calcSign(clientId,accessToken,timestamp,nonce,signStr,secret){
  
    var str = clientId + accessToken +timestamp + nonce + signStr;
    var hash = CryptoJS.HmacSHA256(str, secret);
    var hashInBase64 = hash.toString();
    var signUp = hashInBase64.toUpperCase();
    return signUp;
}

// 生成签名字符串
function stringToSign(query, method){
    var sha256 = "";
    var url = "";
    var headersStr = ""
    
    var map = {}
    var arr = []
    var bodyStr = ""
    if(query){
        toJsonObj(query, arr, map)
    }
   
    sha256 = CryptoJS.SHA256(bodyStr)
    arr = arr.sort()
    arr.forEach(function(item){
            url += item + "=" + map[item] + "&"
    })
    if (url.length > 0 ) {
        url = url.substring(0, url.length-1)
        url = "/" + "v1.0/devices/6cd2bd75ba8a2e86f98jrt/status" + "?" + url
    } else {
        url = "/" + "v1.0/devices/6cd2bd75ba8a2e86f98jrt/status"
    }
    
    
    

 
    map["signUrl"] = method + "\n" + sha256 + "\n" + headersStr + "\n" + url
    map["url"] = url
    return map
}








function toJsonObj(params, arr, map){
    var jsonBodyStr = JSON.stringify(params)
    var jsonBody = JSON.parse(jsonBodyStr)
    jsonBody.forEach(function(item){
        if(!item.disabled){
            arr.push(item.key)
            map[item.key] = item.value
        }
    })
}
